//
//  PPHomeAlbumListView.m
//  pickpic
//
//  Created by Jinxiao on 9/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPHomeAlbumListView.h"

#import "PPHomeEmptyTableViewCell.h"
#import "PPHomeAlbumTableViewCell.h"

#import "PPProgressiveLogoView.h"
#import "PPHomeAlbumTableUtilityButton.h"

#import "PPAlbumModel.h"
#import "PPAlbumImageModel.h"

#import "PPAlbumManager.h"

#define LogoHeaderHeight    110

@interface PPHomeAlbumListView () <UITableViewDelegate, UITableViewDataSource, SWTableViewCellDelegate>
@property (readwrite, nonatomic, strong) UIView *backgroundView;
@property (readwrite, nonatomic, strong) UIView *whiteBackgroundView;
@property (readwrite, nonatomic, strong) PPAbstractTableView *tableView;
@property (readwrite, nonatomic, strong) PPProgressiveLogoView *logoView;
@property (readwrite, nonatomic, strong) UIView *headerView;
@property (readwrite, nonatomic, strong) UIImageView *backgroundImageView;
@property (readwrite, nonatomic, strong) NSArray <PPAlbumModel *> *albums;

@property(nonatomic,retain)UIActivityIndicatorView *act;
@end

@implementation PPHomeAlbumListView

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];

    if([self shouldHideUtilities]) {
        if([view isKindOfClass:[PPHomeAlbumTableUtilityButton class]]) {
            return view;
        } else {
            [self hideUtilitiesIfNeeded];

            return nil;
        }
    } else {
        return view;
    }
}

- (instancetype)init {
    self = [super init];

    self.clipsToBounds = NO;
    self.backgroundColor = [UIColor whiteColor];

    _backgroundView = [[UIView alloc] init];
    _backgroundView.backgroundColor = [UIColor clearColor];
    [self addSubview:_backgroundView];
    
    self.act=[[UIActivityIndicatorView  alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-10, 20, 20, 20)];
    //设置 风格;
    self.act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    //设置活动指示器的颜色
//    self.act.color=[UIColor redColor];
    //hidesWhenStopped默认为YES，会隐藏活动指示器。要改为NO
    self.act.hidesWhenStopped=NO;
    //启动
//    [self.act startAnimating];

    [_backgroundView addSubview:self.act];

//    _backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"color－backg"]];
//    [_backgroundView addSubview:_backgroundImageView];

//    _whiteBackgroundView = [[UIView alloc] init];
//    _whiteBackgroundView.backgroundColor = [UIColor whiteColor];
//    [_backgroundView addSubview:_whiteBackgroundView];

    _tableView = [[PPAbstractTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorInset = UIEdgeInsetsMake(0, 14, 0, 0);
    _tableView.clipsToBounds = NO;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollsToTop = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView registerNib:[UINib nibWithNibName:@"PPHomeEmptyTableViewCell" bundle:nil] forCellReuseIdentifier:@"emptyCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"PPHomeAlbumTableViewCell" bundle:nil] forCellReuseIdentifier:@"albumCell"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"placeholderCell"];
    [_backgroundView addSubview:_tableView];
//    [self addSubview:_tableView];
    
    self.tableView.mj_header = [YKRefreshHeaderDIY headerWithRefreshingTarget:self refreshingAction:@selector(loadAlbums:)];
//    [self.tableView.mj_header beginRefreshing];
    
    _headerView = [[UIView alloc] init];
    _headerView.backgroundColor = [UIColor clearColor];
    _headerView.clipsToBounds = NO;
    _tableView.tableHeaderView = _headerView;

//    _logoView = [[PPProgressiveLogoView alloc] init];
//    _logoView.logoColor = [UIColor colorWithRGBHex:0xffffff];
//    _logoView.clipsToBounds = NO;
//    _logoView.backgroundColor = [UIColor clearColor];
//    [_headerView addSubview:_logoView];

    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor whiteColor];
    footerView.frame = CGRectMake(0, 0, CGFLOAT_MIN, CGFLOAT_MIN);
    _tableView.tableFooterView = footerView;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveLocalAlbumsChangedNotification) name:PPAlbumManagerDidChangeLocalAlbumsNotification object:nil];

    return self;
}



- (void)loadAlbums:(YKRefreshHeader *)refresh{
//    self.act.hidesWhenStopped = NO;
    [self.act startAnimating];
    
//    [UIView animateWithDuration:0.3 animations:^{
////        self.act.hidesWhenStopped = YES;
////        [self.act stopAnimating];
//    } completion:^(BOOL finished) {
//        [refresh endRefreshing];
//    }];
    

//    if (refresh.state == MJRefreshStatePulling) {
//         [self.act stopAnimating];
        [refresh endRefreshing];
//    }
    
}
- (void)didReceiveLocalAlbumsChangedNotification {
    [self reloadDatas];
}

- (void)didMoveToSuperview {
    [self reloadDatas];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _backgroundView.frame = self.bounds;

    _backgroundImageView.frame = _backgroundView.bounds;
    _whiteBackgroundView.frame = _backgroundView.bounds;
    _tableView.frame = _backgroundView.bounds;

    _headerView.frame = CGRectMake(0, 0, _tableView.width, _tableView.height);
    _tableView.tableHeaderView = _headerView;

    _logoView.frame = _headerView.bounds;

    _tableView.contentInset = UIEdgeInsetsMake(-_headerView.height, 0, 0, 0);
    
}


- (void)dismissWithDuration:(NSTimeInterval)duration animated:(BOOL)animated completion:(void (^)(void))completion {
    UIView *container = [_logoView valueForKey:@"container"];

    CGFloat offset = -_tableView.contentOffset.y + _headerView.height;

    if(animated) {
        [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(4 << 16) animations:^{
            _tableView.top = self.height;
            _headerView.alpha = 0;
            container.top = offset - (offset + container.height)/2;
            _whiteBackgroundView.top = self.height;
        } completion:^(BOOL finished) {
            !completion ? : completion();
        }];
    } else {
        _tableView.top = self.height;
        _headerView.alpha = 0;
        container.top = offset - (offset + container.height)/2;
        _whiteBackgroundView.top = self.height;
        !completion ? : completion();
    }
}

- (void)reset {
    _tableView.top = 0;
    _whiteBackgroundView.top = 0;
    _headerView.alpha = 1;
}

- (void)reloadDatas {
    _albums = [PPAlbumModel where:@{@"deleted" : @(NO)} order:@{@"update" : @"desc"}];
    [_tableView reloadData];
    
    
    if ([self.delegate respondsToSelector:@selector(listView:listAlbumData:)]) {
        [self.delegate listView:self listAlbumData:_albums];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(_albums.count == 0) {
        return 1 + 1;
    } else {
        return _albums.count + 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
        return CGFLOAT_MIN;
    } else {
        return 94;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;

    if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"placeholderCell" forIndexPath:indexPath];
    } else if(_albums.count == 0) {
        PPHomeEmptyTableViewCell *cell = (PPHomeEmptyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"emptyCell" forIndexPath:indexPath];
        [cell.firstEbookBtn addTarget:self action:@selector(didSelectBtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.firstEbookBtn.hidden = YES;
        [cell.coverBtn addTarget:self action:@selector(didCreateAlum:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"albumCell" forIndexPath:indexPath];

        ((PPHomeAlbumTableViewCell *)cell).album = [_albums safeObjectAtIndex:indexPath.row];

        NSMutableArray *rightButtons = [NSMutableArray array];

        NSArray *colors = @[/*[UIColor colorWithRGBHex:0xc7c7c7], [UIColor colorWithRGBHex:0xffdd17], */[UIColor colorWithRGBHex:0xff3a2f]];
        NSArray *titles = @[/*@"编辑", @"分享", */@"删除"];

        for(NSInteger index = 0; index < titles.count; index++) {
            PPHomeAlbumTableUtilityButton *button = [PPHomeAlbumTableUtilityButton buttonWithType:UIButtonTypeCustom];
            button.backgroundColor = colors[index];
            [button setTitle:titles[index] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button.titleLabel setAdjustsFontSizeToFitWidth:YES];
            [rightButtons addObject:button];
        }

        ((PPHomeAlbumTableViewCell *)cell).rightUtilityButtons = rightButtons;
        ((PPHomeAlbumTableViewCell *)cell).delegate = self;
        
        ((PPHomeAlbumTableViewCell *)cell).eBookBtn.tag = indexPath.row;
        ((PPHomeAlbumTableViewCell *)cell).rightBgView.tag = indexPath.row;
        [((PPHomeAlbumTableViewCell *)cell).eBookBtn addTarget:self action:@selector(clickEbook:) forControlEvents:UIControlEventTouchUpInside];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickEbook:)];
        [((PPHomeAlbumTableViewCell *)cell).rightBgView addGestureRecognizer:tap];
        
    }

    return cell;
}
- (void)clickEbook:(id)sender{

    
    if ([sender isKindOfClass:[UITapGestureRecognizer class]]) {
        UITapGestureRecognizer *rec = sender;
        
        if([rec.view isKindOfClass:[UIView class]]){
            UIView *view = (UIView *)rec.view;
            
            
            PPHomeAlbumTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:view.tag inSection:0]];
            if ([cell.countLabel.text isEqualToString:@"0张"]) {
                [self toastMessage:@"相册封面加载失败"];
                return;
            }
            
            if ([self.delegate respondsToSelector:@selector(listView:didSelectEbookAlbum:)]) {
                [self.delegate listView:self didSelectEbookAlbum:self.albums[view.tag]];
            }
        }
    }
    
    if ([sender isKindOfClass:[UIButton class]]) {
        UIButton *btn = sender;
        PPHomeAlbumTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0]];
        if ([cell.countLabel.text isEqualToString:@"0张"]) {
            [self toastMessage:@"相册封面加载失败"];
            return;
        }
        if ([self.delegate respondsToSelector:@selector(listView:didSelectEbookAlbum:)]) {
            [self.delegate listView:self didSelectEbookAlbum:self.albums[btn.tag]];
        }
    }
    
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if(_albums.count == 0) {
        [_delegate listViewDidSelectCreateAlbum:self];
    } else {
        PPAlbumModel *album = [_albums safeObjectAtIndex:indexPath.row];;

        [_delegate listView:self didSelectAlbum:album];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat minimumOffset = 0;
    CGFloat maximumOffset = 110;

    CGFloat offset = -scrollView.contentOffset.y + _headerView.height;

    CGFloat progress = (offset - minimumOffset)/(maximumOffset - minimumOffset);

    _whiteBackgroundView.top = offset;

    _logoView.progress = progress;

    _logoView.offset = offset;

    if(offset <= 0) {
        _backgroundImageView.top = offset;
    } else {
        _backgroundImageView.top = 0;
    }
}
- (void)didSelectBtn:(UIButton *)btn{
    [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    if(_logoView.progress >= 1) {
        [_delegate listViewDidTriggerToggling:self];
    }
}

- (void)triggerDismiss {
    [_delegate listViewDidTriggerToggling:self];
}

#pragma mark - SWTableViewCellDelegate

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];

    PPAlbumModel *album = [_albums safeObjectAtIndex:indexPath.row];

    if(index == 0) {
        /*
        [_delegate listView:self didSelectEditAlbum:album];
    } else if(index == 1) {
        [_delegate listView:self didSelectShareAlbum:album];
    } else {
         */
        [_delegate listView:self didSelectDeleteAlbum:album];
    }

    [cell hideUtilityButtonsAnimated:YES];
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell {
    return YES;
}

- (BOOL)shouldHideUtilities {
    __block BOOL result = NO;
    [self.tableView.visibleCells enumerateObjectsUsingBlock:^(__kindof UITableViewCell *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if([obj isKindOfClass:[SWTableViewCell class]]) {
            if(![((SWTableViewCell *)obj) isUtilityButtonsHidden]) {
                result = YES;
                *stop = YES;
            }
        }
    }];

    return result;
}

- (BOOL)hideUtilitiesIfNeeded {
    __block BOOL result = NO;
    [self.tableView.visibleCells enumerateObjectsUsingBlock:^(__kindof UITableViewCell *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if([obj isKindOfClass:[SWTableViewCell class]]) {
            if(![((SWTableViewCell *)obj) isUtilityButtonsHidden]) {
                [((SWTableViewCell *)obj) hideUtilityButtonsAnimated:YES];
                result = YES;
            }
        }
    }];

    return result;
}

- (void)didCreateAlum:(id)sender{

    if ([self.delegate respondsToSelector:@selector(listViewWithCreateAlbum)]) {
        [self.delegate listViewWithCreateAlbum];
    }
}
@end
